package com.sky.config;

import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.interceptor.JwtTokenUserInterceptor;
import com.sky.json.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.List;

/**
 * 配置类，注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    //注入管理员JWT令牌拦截器，验证管理员身份
    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;
    //注入用户JWT令牌拦截器，验证普通用户身份
    @Autowired
    private JwtTokenUserInterceptor jwtTokenUserInterceptor;

    // 从配置文件读取所有图片路径
    @Value("${visa.path.country-images}")
    private String countryImagesPath;

    // 添加新的图片路径配置
    @Value("${visa.path.user-material-images}")
    private String userMaterialImagesPath;

    /**
     * 配置静态资源映射
     * 用于将URL路径映射到服务器本地文件或类路径资源
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始冷却终极技能资源......");
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 映射所有图片资源
        log.info("配置图片资源映射，country路径: {}", countryImagesPath);
        log.info("配置图片资源映射，material路径: {}", userMaterialImagesPath);
        //配置用户材料图片的访问路径映射
        registry.addResourceHandler("/admin/images/usermaterial/**")
                .addResourceLocations("file:" + userMaterialImagesPath);
        //配置通用图片访问路径
        registry.addResourceHandler("/images/**")
                .addResourceLocations(
                        "file:" + countryImagesPath,
                        "file:" + userMaterialImagesPath
                );
    }

    /**
     * 注册拦截器
     * 用于对请求进行前置处理（身份验证、权限校验）
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("结果被拦截器给拦截了TAT......");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns(
                        "/admin/login",
                        "/admin/employee/login",
                        "/admin/user/wxLogin",
                        "/admin/user/address",
                        "/admin/user/bindPhone",
                        "/admin/user/proposal",
                        "/admin/user/proposal/list",
                        "/admin/user/proposal/{id}",
                        "/admin/order/upload",
                        "/admin/pay/payment",
                        "/admin/pay/notify",
                        "/admin/pay/refund",
                        "/admin/order/updateStatus",
                        "/admin/order/pageinfo",
                        "/admin/material/fields/all",
                        "/admin/file/upload",
                        "/admin/visa/template",
                        "/api/templates/list",
                        "/admin/formtemplate/add",
                        "/admin/formUserMateri/upload",
                        "/admin/material/submit",
                        "/admin/images/usermaterial/upload",
                        "/admin/material/fields",
                        "/admin/user/document/uploadMarriage")
                .excludePathPatterns("/admin/account/**")
                .excludePathPatterns("/admin/country/public/**")
                .excludePathPatterns("/images/**",
                        "/admin/user/document/uploadPhoto");
        registry.addInterceptor(jwtTokenUserInterceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/user/login")
                .excludePathPatterns("/user/shop/status");
    }

    /**
     * 跨域配置
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(false)
                .maxAge(3600);
    }

    /**
     * 通过knife4j生成接口文档
     * @return
     */
    @Bean
    public Docket docket() {
        log.info("难过了......准备打盹......");
        //构建API文档信息
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("签证项目接口文档")
                .version("2.0")
                .description("签证项目接口文档")
                .build();
        //创建docket对象，配置文档扫描范围
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    @Bean
    public Docket docket2() {
        log.info("开始摸鱼......");
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("签证项目接口文档")
                .version("2.0")
                .description("签证项目接口文档")
                .build();

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .groupName("用户端接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller.user"))
                .paths(PathSelectors.any())
                .build();

        return docket;
    }

    /**
     * 扩展消息转换器
     * 自定义JSON序列化/反序列化规则
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("宁の力量正在准备消息转换器终极能量......");
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(new JacksonObjectMapper());
        converters.add(0, converter);
    }
}
